package com.atguigu.yygh.hosp.listener;

import com.atguigu.yygh.hosp.service.ScheduleService;
import com.atguigu.yygh.model.hosp.Schedule;
import com.atguigu.yygh.rabbitmq.config.MQProperties;
import com.atguigu.yygh.rabbitmq.service.RabbitmqService;
import com.atguigu.yygh.vo.hosp.ScheduleOrderVo;
import com.atguigu.yygh.vo.msm.SmsVo;
import com.atguigu.yygh.vo.order.OrderMqVo;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import io.swagger.annotations.Api;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


/**
 * @Author zhmwi
 * @Date 2021/7/23
 * @Dersciption
 */
@Component
@Api("排班信息的监听")
public class MQHospitalListener {

    @Autowired
    private ScheduleService scheduleService;

    @Autowired
    private RabbitmqService rabbitmqService;

    //监听下单更新预约数还是取消订单更新预约数
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MQProperties.QUEUE_ORDER,durable = "true"),
            exchange = @Exchange(MQProperties.EXCHANGE_DIRECT_ORDER),
            key = {MQProperties.ROUTING_ORDER}
    ))
    public void updateAvailableNumberAndSendMessage(OrderMqVo orderMqVo, Message message, Channel channel){
        //判断是下单更新预约数还是取消订单更新预约数
        if (orderMqVo.getAvailableNumber() == null){
            //取消预约加库存
            Schedule schedule = scheduleService.getScheduleById(orderMqVo.getScheduleId());
            schedule.setAvailableNumber(orderMqVo.getAvailableNumber().intValue()+1);
            scheduleService.updateSchedule(schedule);
        }else{
            //下单减库存
            Schedule schedule = scheduleService.getScheduleById(orderMqVo.getScheduleId());
            //总预约数
            schedule.setReservedNumber(orderMqVo.getReservedNumber());
            //剩余预约数
            schedule.setAvailableNumber(orderMqVo.getAvailableNumber());
            scheduleService.updateSchedule(schedule);
        }


        //发送短信
        SmsVo smsVo = orderMqVo.getSmsVo();
        if (smsVo == null){
            rabbitmqService.sendMessage(MQProperties.EXCHANGE_DIRECT_MSM,MQProperties.ROUTING_MSM_ITEM,smsVo);
        }
    }
}
